package controllers

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
	"fmt"
)

type Validation struct {
	beego.Controller
}

type Worker struct {
	Name string `form:"name"`
	Age int `form:"age"`
	Mobile string  `form:"mobile"`
	Address string  `form:"address"`
}

func (this *Validation) Get() {
	this.TplName = "worker.html"
}

// 使用this.GetString 获取每一个值 但是很麻烦 还有一种 快捷的 直接解析到结构体中
func (this *Validation) PostCopy() {
	name := this.GetString("name")
	age, err := this.GetInt("age")
	if err != nil {
		age = 0
	}
	mobile := this.GetString("mobile")
	address := this.GetString("address")
	workder := Worker{name, age, mobile, address}
	fmt.Println(workder)
	// 创建校验对象
	valid := validation.Validation{}
	// 校验姓名不能为空
	result := valid.Required(workder.Name, "name")
	errmessage := make(map[string]string)
	if !result.Ok {
		fmt.Println("姓名为空")
		errmessage["name"] = "姓名不能为空"
	}
	// 校验年龄是否在18到60之间
	result = valid.Range(workder.Age, 18, 60, "age")
	if !result.Ok {
		fmt.Println("年龄不合法")
		errmessage["age"] = "年龄不合法"
	}
	// 校验手机号码不合法
	result = valid.Mobile(workder.Mobile, "mobile")
	if !result.Ok {
		fmt.Println("手机号码不合法")
		errmessage["mobile"] = "手机号码不合法"
	}
	// 地址为空
	result = valid.Required(workder.Address, "address")
	if !result.Ok {
		fmt.Println("地址为空")
		errmessage["address"] = "地址不能为空"
	}
	if len(errmessage) == 0 {
		// this.Ctx.WriteString("表单数据验证成功")
		this.Data["json"] = workder
		this.ServeJSON()
		// this.Data["xml"] = worker
		// this.ServeXML()
		this.TplName = "output.tpl"
	} else {
		this.TplName = "worker.html"
	}
}

// 将表单数据直接解析到结构体中, 结构体中的别名 需要名称和form一样
func (this *Validation) Post() {
	var workder Worker
	if err := this.ParseForm(&workder); err != nil {
		this.Ctx.WriteString("亲 出错了")
	} else {
		fmt.Println(workder)
		this.Ctx.WriteString("解析成功")
	}
}

